package com.erp.order.purchasing.service.impl;

import com.erp.hr.base.service.impl.BaseServiceImpl;
import com.erp.hr.base.util.CommonUtils;
import com.erp.hr.base.vo.LegalityResultVO;
import com.erp.hr.base.vo.ResultVO;
import com.erp.masterdata.vendor.service.MdVendorService;
import com.erp.order.purchasing.dao.PurchaseOrderDao;
import com.erp.order.purchasing.model.InquiryList;
import com.erp.order.purchasing.model.PurchaseOrder;
import com.erp.order.purchasing.model.PurchaseOrderDetailVO;
import com.erp.order.purchasing.model.PurchasingRequisitionDetail;
import com.erp.order.purchasing.service.*;
import org.redragon.framework.hibernate.model.Pages;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.util.*;


/**
 * 询价单 业务实现层
 * @Author: syz
 * @blame syz
 * @CreateTime: 2021/4/6
 */
@Service
public class PurchaseOrderServiceImpl extends BaseServiceImpl<PurchaseOrderDao, PurchaseOrder> implements PurchaseOrderService {

    /**
     * 询价单服务
     */
    @Lazy
    @Autowired
    private InquiryListService inquiryListService;

    /**
     * 供应商服务
     */
    @Lazy
    @Autowired
    private MdVendorService mdVendorService;

    /**
     * 申请详情服务
     */
    @Lazy
    @Autowired
    private PurchasingRequisitionDetailService purchasingRequisitionDetailService;

    /**
     * 采购订单服务
     */
    @Lazy
    @Autowired
    private PurchaseOrderService purchaseOrderService;


    /**
     * 为单个对象添加完整信息
     * @param purchaseOrder 需要添加完整信息的对象
     * @return 添加完整信息后的对象
     */
    @Override
    public PurchaseOrder addCompleteData(PurchaseOrder purchaseOrder) {
        purchaseOrder.setSubs(dao.getSubInfo(purchaseOrder.getId()));
        return purchaseOrder;
    }

    @Override
    public List<PurchaseOrder> addCompleteData(List<PurchaseOrder> list) {
        return list;
    }

    @Override
    public List<PurchaseOrder> getDatasBySupplyid(String username,PurchaseOrder purchaseOrder, Pages pages) {
        return dao.getDatasBySupplyid(username,purchaseOrder,pages);
    }

    @Override
    public PurchaseOrder getDataObject(Long id) {
        return dao.getDataObject(id);
    }

    /**
     * 将询价单转换为采购订单
     * @param id 询价单id
     */
    @Override
    public void inquiryListToPurchaseOrder(Long id) {
        InquiryList inquiryList = inquiryListService.getDataObject(id.toString());
        if (CommonUtils.PROCUREMENT_TYPE_ONLY.equals(inquiryList.getProcurementType())) {
            orderByOnly(inquiryList);
        } else {
            if (CommonUtils.INQUIRY_TYPE_1688.equals(inquiryList.getInquiryType())) {
                orderBy1688(inquiryList);
            } else {
                orderByOther(inquiryList);
            }
        }
    }

    /**
     * 设置订单金额
     * @param purchaseOrder 采购订单对象
     * @return 设置结果
     */
    @Override
    public ResultVO<String> setMoney(PurchaseOrder purchaseOrder) {
        try {
            PurchaseOrder po = getDataObject(purchaseOrder.getId());
            po.setTotalMoney(purchaseOrder.getTotalMoney());
            setUpdateInfo(po);
            updateDataObject(po);
            return ResultVO.success();
        } catch (Exception e) {
            return ResultVO.error("设置失败");
        }
    }

    /**
     * 更新订单状态
     * @param id 采购订单id
     * @return 更新结果
     */
    @Override
    public ResultVO<String> changeStatus(String id) {
        try {
            PurchaseOrder po = getDataObject(id);
            if (!new BigDecimal("0.00").equals(po.getTotalMoney())) {
                po.setStatus(CommonUtils.PURCHASE_ORDER_STATUS_SHIPMENT);
                setUpdateInfo(po);
                updateDataObject(po);
                return ResultVO.success();
            }
            return ResultVO.error("请先设置订单金额");
        } catch (Exception e) {
            return ResultVO.error("更新失败");
        }
    }

    /**
     * 单一采购订单
     * @param inquiryList 询价单对象
     */
    private void orderByOnly(InquiryList inquiryList) {
        inquiryList.setStatus(CommonUtils.INQUIRY_LIST_STATUS_ANSWER_END);
        setUpdateInfo(inquiryList);
        inquiryListService.updateDataObject(inquiryList);
        createPurchaseOrder(inquiryList.getId(), purchasingRequisitionDetailService.getOnlyOrderDetail(inquiryList.getId()));
    }

    /**
     * 1688订单
     * @param inquiryList 询价单对象
     */
    private void orderBy1688(InquiryList inquiryList) {

    }

    /**
     * 询比价订单
     * @param inquiryList 询价单对象
     */
    private void orderByOther(InquiryList inquiryList) {
        inquiryList.setStatus(CommonUtils.INQUIRY_LIST_STATUS_APPROVAL_END);
        setUpdateInfo(inquiryList);
        inquiryListService.updateDataObject(inquiryList);
        createPurchaseOrder(inquiryList.getId(), purchasingRequisitionDetailService.getOtherOrderDetail(inquiryList.getId()));
    }

    /**
     * 创建采购订单
     * @param inquiryListId 询价单id
     * @param list 采购详情集合
     */
    private void createPurchaseOrder(Long inquiryListId, List<PurchaseOrderDetailVO> list) {
        InquiryList inquiryList = inquiryListService.getDataObject(inquiryListId.toString());
        String status = CommonUtils.PROCUREMENT_TYPE_ONLY.equals(inquiryList.getProcurementType())
                ? CommonUtils.PURCHASE_ORDER_STATUS_DRAFT
                : CommonUtils.PURCHASE_ORDER_STATUS_SHIPMENT;
        Set<Integer> suppliers = new HashSet<>();
        Map<String, List<String>> addresses = new HashMap<>();
        for (PurchaseOrderDetailVO po : list) {
            suppliers.add(po.getSupplierId());
            addresses.put(
                    po.getAddress(),
                    new ArrayList<String>(4) {{
                        add(po.getCompanyName());
                        add(po.getLinkman());
                        add(po.getTel());
                    }});
        }
        for (Integer supplier : suppliers) {
            for (String address : addresses.keySet()) {
                boolean hasOrder = false;
                List<String> value = addresses.get(address);
                PurchaseOrder purchaseOrder = new PurchaseOrder();
                purchaseOrder.setInquiryListId(inquiryListId);
                setCode(purchaseOrder);
                purchaseOrder.setSupplierId(supplier);
                purchaseOrder.setSupplierName(mdVendorService.getDataObject(supplier).getVendorName());
                purchaseOrder.setCompanyName(value.get(0));
                purchaseOrder.setLinkman(value.get(1));
                purchaseOrder.setTel(value.get(2));
                purchaseOrder.setBeginDate(inquiryList.getBeginDate());
                purchaseOrder.setEndDate(inquiryList.getEndDate());
                purchaseOrder.setAddress(address);
                purchaseOrder.setAmountPaid(new BigDecimal("0"));
                BigDecimal totalMoney = new BigDecimal("0");
                Set<Long> ids = new HashSet<>();
                Iterator<PurchaseOrderDetailVO> iter = list.iterator();
                while (iter.hasNext()) {
                    PurchaseOrderDetailVO next = iter.next();
                    if (next.getSupplierId().equals(supplier) && next.getAddress().equals(address)) {
                        hasOrder = true;
                        ids.add(next.getId());
                        totalMoney = totalMoney.add(new BigDecimal(next.getPrice()).multiply(new BigDecimal(next.getQuantity().toString())));
                        iter.remove();
                    }
                }
                if (hasOrder) {
                    purchaseOrder.setTotalMoney(totalMoney);
                    purchaseOrder.setStatus(status);
                    setCreateInfo(purchaseOrder);
                    purchaseOrderService.insertDataObject(purchaseOrder);
                    List<PurchasingRequisitionDetail> prdList = purchasingRequisitionDetailService.getByIds(ids);
                    for (PurchasingRequisitionDetail prd : prdList) {
                        prd.setPurchaseOrderId(purchaseOrder.getId());
                        setUpdateInfo(prd);
                        purchasingRequisitionDetailService.updateDataObject(prd);
                    }
                }
            }
        }
    }

    /**
     * 设置订单编号
     * @param purchaseOrder 需要设置订单编号的对象
     */
    private void setCode(PurchaseOrder purchaseOrder) {
        StringBuilder sb = new StringBuilder();
        sb.append(CommonUtils.PREFIX_PURCHASE_ORDER);
        Calendar calendar = Calendar.getInstance();
        sb.append(calendar.get(Calendar.YEAR));
        sb.append(calendar.get(Calendar.MONTH) + 1);
        sb.append(calendar.get(Calendar.DATE));
        sb.append(getCodeSuffix());
        purchaseOrder.setCode(sb.toString());
    }

    /**
     * 获取询价编号后缀
     * @return 询价编号后缀
     */
    private String getCodeSuffix() {
        Integer num = dao.getCreateCount() + 1;
        String suffix = num.toString();
        StringBuilder result = new StringBuilder();
        for (int i = 0; i < CommonUtils.PURCHASING_REQUISITION_LENGRH - suffix.length(); i ++) {
            result.append("0");
        }
        result.append(suffix);
        return result.toString();
    }

    @Override
    public LegalityResultVO isLegalityData(PurchaseOrder purchaseOrder) {
        return null;
    }

    @Override
    public boolean save(PurchaseOrder purchaseOrder) {
        return false;
    }

    @Override
    public boolean update(PurchaseOrder purchaseOrder) {
        return false;
    }

    @Override
    public boolean linkDelete(Long id) {
        return false;
    }

}